package net.fdukedom.epicurus.presentation.actions.pub;

import net.fdukedom.epicurus.presentation.actions.AbstractForm;
import net.fdukedom.epicurus.domain.util.UserHelper;
import net.fdukedom.epicurus.domain.entity.User;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

import javax.servlet.http.HttpServletRequest;

/**
 * Bean for login form.
 *
 * @author Dmitry Y. Kochelaev
 */
public class LoginForm extends AbstractForm {

    /**
     * User email.
     */
    private String email;

    /**
     * User password.
     */
    private String password;

    private UserHelper userHelper = UserHelper.getInstance();

    public ActionErrors doValidate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        User user = userHelper.findByEmail(email);
        if (user == null || !user.getPassword().equals(User.hash(password))) {
            errors.add("error.login.failed", new ActionMessage("login.errors.failed"));
            return errors;
        }
        if (!user.getIsActivated()) {
            errors.add("error.login.failed", new ActionMessage("login.errors.notActivated"));
        }
        return errors;
    }

    public void doReset(ActionMapping mapping, HttpServletRequest request) {
        email = "";
        password = "";
    }

    /**
     * Returns user email.
     *
     * @return user email
     */
    public String getEmail() {
        return email;
    }

    /**
     * Sets user email.
     *
     * @param email user email
     */
    public void setEmail(String email) {
        this.email = email;
    }

    /**
     * Returns user password.
     *
     * @return user password
     */
    public String getPassword() {
        return password;
    }

    /**
     * Sets user password.
     *
     * @param password user password
     */
    public void setPassword(String password) {
        this.password = password;
    }

}
